import {
  Provide, Controller, Post, Get, Del, File, Inject, Body, Query, Param,
} from '@midwayjs/core';
import { StationDataService } from '../service/station-data.service';
import { Context } from '@midwayjs/koa';
import {
  StationFileUploadResultDTO, StationMetaCreateDTO, StationMetaListDTO, IdDTO,FileKeyQueryDTO 
} from '../dto/station-data.dto';
import { ApiBody, ApiTags } from '@midwayjs/swagger';
import { BodyContentType } from '@midwayjs/swagger';
import * as fs from 'fs';

@Provide()
@ApiTags(['测站文件管理'])
@Controller('/api/station-data')
export class StationDataController {
  @Inject()
  ctx: Context;

  @Inject()
  stationDataService: StationDataService;

  /** 1. 单独上传 */
  @Post('/upload', { summary: '上传测站数据Excel' })
  @ApiBody({
    description: '上传Excel文件',
    contentType: BodyContentType.Multipart,
  })
  async fileUpload(
    @File() file: any
  ): Promise<{ success: true, data: StationFileUploadResultDTO }> {
    console.dir(file, { depth: 10 });  // 打印 file 的内容
    const result = await this.stationDataService.saveUploadFile(file);
    return { success: true, data: result };
  }

  /** 2. 登记元信息 */
  @Post('/meta', { summary: '登记测站Excel元信息' })
  @ApiBody({
    type: StationMetaCreateDTO,
    description: '元信息DTO',
  })
  async metaRegister(
    @Body() body: StationMetaCreateDTO
  ) {
    const res = await this.stationDataService.createMetaInfo(body);
    return { success: true, data: res };
  }

  /** 3. 列表分页 */
  @Get('/meta/list', { summary: '登记元信息列表' })
  async list(@Query() query: StationMetaListDTO) {
    const { page = 1, pageSize = 10 } = query;
    const result = await this.stationDataService.metaList(query, Number(page), Number(pageSize));
    return { success: true, ...result };
  }

  /** 4. 下载接口（新：用query参数） */
  @Get('/download', { summary: '下载已上传文件' })
  async download(@Query() query: FileKeyQueryDTO) {
    const { fileKey } = query;
    const fileInfo = await this.stationDataService.getFileByKey(fileKey);
    if (!fileInfo) {
      this.ctx.status = 404;
      this.ctx.body = 'File not found';
      return;
    }
    this.ctx.set('Content-Type', fileInfo.mimeType);
    this.ctx.set('Content-Disposition', `attachment; filename="${encodeURIComponent(fileInfo.originalName)}"`);
    this.ctx.body = fs.createReadStream(fileInfo.filePath);
  }


  /** 5. 元数据信息删除 */
  @Del('/meta/:id', { summary: '删除元信息' })
  async deleteMeta(@Param() param: IdDTO) {
    await this.stationDataService.deleteMeta(param.id);
    return { success: true };
  }
}
